package com.quanyan.user.service.impl;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.Lists;
import com.quanyan.api.APIResponse;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.enums.SysCategoryEnum;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.user.constants.UserConstants;
import com.quanyan.user.mapper.TbInterestMapper;
import com.quanyan.user.mapper.TbUserInterestMapper;
import com.quanyan.user.mapper.UserInterestMapper;
import com.quanyan.user.model.db.TbInterest;
import com.quanyan.user.model.db.TbInterestExample;
import com.quanyan.user.model.db.TbUserInterest;
import com.quanyan.user.model.db.TbUserInterestExample;
import com.quanyan.user.model.enums.LarkOfficialAccountEnum;
import com.quanyan.user.model.vo.request.ReqUserInterest;
import com.quanyan.user.model.vo.response.RespUserInterest;
import com.quanyan.user.model.vo.response.RespUserSelectInterest;
import com.quanyan.user.response.RespOpenUserInterest;
import com.quanyan.user.service.HttpClientService;
import com.quanyan.user.service.UserInterestService;
import com.quanyan.user.service.UserRelationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yue.yuan on 2016/6/28.
 */
@Service("userInterestService")
public class UserInterestServiceImpl implements UserInterestService{

    private static final Logger logger = LoggerFactory.getLogger(UserInterestServiceImpl.class);

    @Autowired
    private TbInterestMapper tbInterestMapper;

    @Autowired
    private UserInterestMapper userInterestMapper;

    @Autowired
    private TbUserInterestMapper tbUserInterestMapper;

    @Autowired
    private HttpClientService httpClientService;

    @Autowired
    private UserRelationService userRelationService;

    /**
     * 查询系统兴趣列表
     * @return APIResponse<RespUserInterest>
     */
    @Override
    public APIResponse<List<RespUserInterest>> selectInterestsByExample()
    {
        List<TbInterest> list = queryInterests();
        List<RespUserInterest> rsp = new ArrayList<>();
        getObtainRsp(list, rsp);
        return APIResponse.returnSuccess(rsp);
    }

    /**
     * 查询用户兴趣列表
     * @return
     */
    @Override
    public APIResponse<List<RespUserInterest>> selectUserInterestsByExample(ReqUserInterest req, Integer uid)
    {
        Integer userType = req.getUserType();
        String dsn = req.getDsn();

        Map map = new HashMap();
        map.put("userType",userType);
        map.put("dsn",dsn);
        map.put("uid",uid);
        List<RespUserInterest> respUserInterestList = this.userInterestMapper.getUserInterestList(map);
        if (respUserInterestList.isEmpty()) {
            //个人兴趣为空，对兴趣进行初始化
            this.batchInsertUserInterest(uid,dsn,userType);
            //获取用户兴趣
            respUserInterestList = this.userInterestMapper.getUserInterestList(map);
        }

        return APIResponse.returnSuccess(respUserInterestList);

    }

    /**
     * 更新个人兴趣
     * @return APIResponse<RespUserInterest>
     */
    @Override
    public APIResponse<RespUserInterest> updateInterests(ReqUserInterest req, Integer uid)
    {
        Integer userType = req.getUserType();
        String dsn = req.getDsn();
        List<Integer> interestList = req.getInterestIds();
        if(null == interestList || interestList.size() == 0)
        {
            return APIResponse.returnFail("兴趣必选");
        }
        else if (userType == UserConstants.USER_VISITOR)
        {
            if(StringUtil.isBlankOrNull(dsn))
            {
                return APIResponse.returnFail("设备编号不正确");
            }
        }
        TbUserInterest userInterest = new TbUserInterest();
        //获取用户当前的兴趣列表
        List<TbUserInterest> userInterestList = this.getUserInterestList(userType,uid,dsn,null);
        if (userInterestList.isEmpty()) {
            this.batchInsertUserInterest(uid,dsn,userType);
        }else{
            userInterest.setIsObtain(UserConstants.USER_INTEREST_IS_NOT_OBTAIN);
            //删除用户兴趣
            this.updateUserInterest(userInterest, null, userType, uid,dsn,null);
        }
        //更新用户兴趣
        userInterest.setIsObtain(UserConstants.USER_INTEREST_IS_OBTAIN);
        Byte isRegister = null;
        if (userType.equals(UserConstants.USER_REGISTER)) {
            isRegister = UserConstants.USER_INTEREST_IS_REGISTER;
        }
        this.updateUserInterest(userInterest,interestList,userType,uid,dsn,isRegister);


            if (userType.equals(UserConstants.USER_REGISTER)) {
                List<Integer> categoryIds = userInterestMapper.getCategoryIdList(interestList);

                //通知c端进行个人兴趣更新
                httpClientService.updateSetting(uid,categoryIds,null,null);
                //关注百灵鸟官方账号
                List<Integer> followIds = new ArrayList<>();
                //百灵鸟官方
                followIds.add(LarkOfficialAccountEnum.LARK_OFFICIAL.getUid());
                //百灵鸟赛事
                followIds.add(LarkOfficialAccountEnum.LARK_MATCH.getUid());
                //百灵鸟俱乐部
                followIds.add(LarkOfficialAccountEnum.LARK_CLUB.getUid());
                for (int categoryId : categoryIds) {
                    if (SysCategoryEnum.BADMINTON.getId() == categoryId) {
                        followIds.add(LarkOfficialAccountEnum.LARK_BADMINTON.getUid());
                        followIds.add(LarkOfficialAccountEnum.LARK_PLACE.getUid());
                    }
                    if (SysCategoryEnum.BASKETBALL.getId() == categoryId) {
                        followIds.add(LarkOfficialAccountEnum.LARK_BASKETBALL.getUid());
                        followIds.add(LarkOfficialAccountEnum.LARK_PLACE.getUid());
                    }
                    if (SysCategoryEnum.CYCLING.getId() == categoryId) {
                        followIds.add(LarkOfficialAccountEnum.LARK_CYCLING.getUid());
                    }
                    if (SysCategoryEnum.FOOTBALL.getId() == categoryId) {
                        followIds.add(LarkOfficialAccountEnum.LARK_FOOTBALL.getUid());
                        followIds.add(LarkOfficialAccountEnum.LARK_PLACE.getUid());
                    }
                    if (SysCategoryEnum.OUTDOORS.getId() ==  categoryId) {
                        followIds.add(LarkOfficialAccountEnum.LARK_OUTDOOR.getUid());
                    }
                    if (SysCategoryEnum.RUN.getId() == categoryId) {
                        followIds.add(LarkOfficialAccountEnum.LARK_RUNNING.getUid());
                    }
                    if (SysCategoryEnum.TENNIS.getId() == categoryId) {
                        followIds.add(LarkOfficialAccountEnum.LARK_TENNIS.getUid());
                        followIds.add(LarkOfficialAccountEnum.LARK_PLACE.getUid());
                    }
                }
                userRelationService.UserFollow(uid,followIds);
            }
        return APIResponse.returnSuccess();
    }



    /**
     *获取系统兴趣列表
     * @return
     */
    private List<TbInterest> queryInterests()
    {
        TbInterestExample example = new TbInterestExample();
        example.createCriteria().andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        return tbInterestMapper.selectByExample(example);
    }

    private List<RespUserInterest> getObtainRsp(List<TbInterest> interests, List<RespUserInterest> rsp) {
        for(TbInterest interest : interests) {
            RespUserInterest resp = new RespUserInterest();
            rsp.add(transferResp(resp, interest));
        }
        return rsp;
    }

    private RespUserInterest transferResp(RespUserInterest resp, TbInterest i)
    {
        resp.setInterestId(i.getId());
        resp.setPriority(i.getPriority());
        resp.setLogUrl(i.getLogUrl());
        resp.setInterestName(i.getName());
        resp.setCategoryId(i.getCategoryId());
        resp.setIsObtain((int)UserConstants.USER_INTEREST_IS_NOT_OBTAIN);
        resp.setSelectUrl(i.getSelectUrl());
        return resp;
    }

    /**
     * 获取用户兴趣列表
     * @param userType
     * @param uid
     * @param dsn
     * @return
     */
    @Override
    public List<TbUserInterest> getUserInterestList(Integer userType,Integer uid,String dsn,Byte isObtain){
        TbUserInterestExample example = new TbUserInterestExample();
        TbUserInterestExample.Criteria criteria = example.createCriteria();
        if(userType.equals(UserConstants.USER_REGISTER)){
            criteria.andUidEqualTo(uid);
        }else if(userType.equals(UserConstants.USER_VISITOR) ){
            criteria.andDsnEqualTo(dsn);
        }
        if (isObtain != null) {
            criteria.andIsObtainEqualTo(isObtain);
        }
        List<TbUserInterest> list = tbUserInterestMapper.selectByExample(example);
        return list;
    }

    /**
     * 批量插入用户兴趣
     * @param uid
     * @param dsn
     * @return
     */
    @Override
    public int batchInsertUserInterest(Integer uid, String dsn, Integer userType) {
        List<TbInterest> interests = this.queryInterests();
        List<TbUserInterest> tbUserInterestList = new ArrayList<>();
        TbUserInterest tbUserInterest;
        for (TbInterest interest : interests) {
            tbUserInterest = new TbUserInterest();
            tbUserInterest.setIsObtain(UserConstants.USER_INTEREST_IS_NOT_OBTAIN);
            if (userType.equals(UserConstants.USER_VISITOR)) {
                tbUserInterest.setDsn(dsn);
                tbUserInterest.setIsRegister(UserConstants.USER_INTEREST_IS_NOT_REGISTER);
            } else if (userType.equals(UserConstants.USER_REGISTER)) {
                tbUserInterest.setUid(uid);
                tbUserInterest.setIsRegister(UserConstants.USER_INTEREST_IS_REGISTER);
            }
            tbUserInterest.setInterestId(interest.getId());
            tbUserInterestList.add(tbUserInterest);
        }
        int n = userInterestMapper.batchInsert(tbUserInterestList);
        return n;
    }

    /**
     * 更新用户兴趣
     * @param userInterest
     * @param userInterestList
     * @param userType
     * @param uid
     * @param dsn
     * @return
     */
    @Override
    public int updateUserInterest(TbUserInterest userInterest,List<Integer> userInterestList,Integer userType,Integer uid,String dsn,Byte isRegister){
        TbUserInterestExample example = new TbUserInterestExample();
        TbUserInterestExample.Criteria criteria = example.createCriteria();
        if(userType.equals(UserConstants.USER_REGISTER)){
            criteria.andUidEqualTo(uid);
        }else if(userType.equals(UserConstants.USER_VISITOR) ){
            criteria.andDsnEqualTo(dsn);
        }
        if (userInterestList != null && !userInterestList.isEmpty()) {
            criteria.andInterestIdIn(userInterestList);
        }
        if (isRegister != null) {
            userInterest.setIsRegister(isRegister);
        }
        int n = this.tbUserInterestMapper.updateByExampleSelective(userInterest,example);
        return n;
    }

    /**
     * 获取用户选中的兴趣列表
     * @param dsn
     * @param uid
     * @param userType
     * @return
     */
    @Override
    public List<RespUserSelectInterest> getUserSelectInterestList(String dsn, Integer uid, Integer userType) {
        Map map = new HashMap();
        map.put("dsn",dsn);
        map.put("uid",uid);
        map.put("userType",userType);
        return userInterestMapper.getUserSelectInterestList(map);
    }

    /**
     * 不推荐使用了，也就不注释啦
     * @param dsn
     * @param uid
     * @param userType
     * @param isObtain
     * @return
     */
    @Override
    public List<RespUserInterest> getUserSelectInterestIdList(String dsn, Integer uid, Integer userType, Byte isObtain) {
        Map map = new HashMap();
        map.put("dsn",dsn);
        map.put("uid",uid);
        map.put("userType",userType);
        map.put("isObtain",isObtain);
        return userInterestMapper.getUserSelectInterestIdList(map);
    }

    /**
     * 批量查询用户兴趣
     * @param uids
     * @return
     */
    @Override
    public Map<Integer, List<RespOpenUserInterest>> batchQueryUserInterest(List<Integer> uids) {
        Map<Integer,List<RespOpenUserInterest>> result = new HashMap<>();
        if (uids == null){
            return result;
        }
        for (Integer uid : uids) {
            List<RespOpenUserInterest> interests = userInterestMapper.getOpenUserInterestList(uid);
            result.put(uid,interests);
        }
        return result;
    }


    public List<Integer>  userInterests(Integer uid){
        List<Integer> lstInterestId = null;//用户标签
        if(uid != null){
            TbUserInterestExample tbUserInterestExample = new TbUserInterestExample();
            TbUserInterestExample.Criteria userInterestCriteria = tbUserInterestExample.createCriteria();
            userInterestCriteria.andUidEqualTo(uid);
            userInterestCriteria.andIsObtainEqualTo((byte) 1);
            List<TbUserInterest> userInterests = tbUserInterestMapper.selectByExample(tbUserInterestExample);
            if (userInterests != null && userInterests.size() > 0) {
                lstInterestId = new ArrayList<>();
                lstInterestId.addAll(coverListByPropertyInterestId(userInterests));
            }
        }
        return lstInterestId;
    }


    //list 按属性生成一个新的 list
    public ImmutableMultiset<Integer> coverListByPropertyInterestId(List<TbUserInterest> lst) {
        return ImmutableMultiset.copyOf(Lists.transform(lst, new Function<TbUserInterest, Integer>() {
                    @Override
                    public Integer apply(TbUserInterest input) {
                        return input.getInterestId();
                    }
                }
        ));
    }

}
